﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MINERP.MODEL.NewProductBigPic;
using MINERP.DAL.NewMakeBigPic;
using System.Net.Sockets;
using System.Configuration;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using MINERP.COM;
using MINERP.DAL;
using MINERP.MODEL.FoundationModel;

namespace MINERP.BLL.NewProductBigPic
{
    //生成大图的主类
    public class MainBLL
    {
        private string _strDogCode = string.Empty;//加密狗的编码，用于加解密
        private const string GETDOGCODE = "GD";//传输命令
        public MainBLL()
        {
            //获得加密狗的ID号用于解密
            //_strDogCode = GetDogCode();
        }

        //获得加密狗的ID号用于解密
        private string GetDogCode()
        {
            string strResult = string.Empty;
            byte[] myReadBuffer = new byte[1024];
            string addr = ConfigurationManager.AppSettings["RemoteIP"].ToString();
            int port = Convert.ToInt32(ConfigurationManager.AppSettings["RemotePort"]);

            string RedStrResult = string.Empty;
            TcpClient client = new TcpClient();
            NetworkStream net = null;

            try
            {
                client.Connect(addr, port);
                client.SendTimeout = 600 * 1000;
                client.ReceiveTimeout = 600 * 1000;
                net = client.GetStream();
                net.ReadTimeout = 600 * 1000;

                byte[] myWriteBuffer = Encoding.Unicode.GetBytes(GETDOGCODE);

                net.Write(myWriteBuffer, 0, myWriteBuffer.Length);

                while (true)
                {
                    int redLenth;
                    try
                    {
                        redLenth = net.Read(myReadBuffer, 0, myReadBuffer.Length);
                    }
                    catch (Exception)
                    {
                        //return -2;//读取失败
                        return string.Empty;
                    }

                    if (redLenth > 0)
                    {
                        strResult = Encoding.Unicode.GetString(myReadBuffer, 0, redLenth);
                        break;
                    }

                }
                net.Close();

                return strResult;
            }
            catch (Exception)
            {
                return string.Empty;
            }
            finally
            {
                client.Close();
                if (net != null)
                {
                    net.Close();
                    net.Dispose();
                }

            }
        }
        /// <summary>
        /// -2代表连联解密的服务器不同，-1解密有错,1正常
        /// </summary>
        /// <param name="b"></param>
        /// <returns>-5:找不到加密狗，-2代表解密出错,-4代表没有可生成的大图</returns>
        public int GetOneBoard(out BoardInfo_ProductBigPic b, int makePicNo)
        {
            b = null;
            //if (string.IsNullOrEmpty(_strDogCode))
            //{
            //    _strDogCode = GetDogCode();
            //    if (string.IsNullOrEmpty(_strDogCode))
            //    {
            //        return -5;
            //    }
            //}

            int result = 1;

            MainDAL _dal = new MainDAL();
            try
            {
                b = _dal.GetOneBoardToMake(makePicNo);
            }
            catch (Exception ex)
            {
                
                WriteLogForCheck.WriteLogFile(ex.ToString());
                return -5;
            }
            AddPrinterInfoToBoard(b);//附加大版的打印机信息
            if (b == null)//没有可用的格子
            {
                return -4;
            }
            //result = DecryPtPoint(b);
            return result;
        }
        /// <summary>
        /// -2代表连联解密的服务器不同，-1解密有错,1正常
        /// </summary>
        /// <param name="b"></param>
        /// <returns>-5:找不到加密狗，-2代表解密出错,-4代表没有可生成的大图</returns>
        public int GetOneBoardAndTiaoseNO(out BoardInfo_ProductBigPic b, int makePicNo)
        {
            b = null;
            //if (string.IsNullOrEmpty(_strDogCode))
            //{
            //    _strDogCode = GetDogCode();
            //    if (string.IsNullOrEmpty(_strDogCode))
            //    {
            //        return -5;
            //    }
            //}

            int result = 1;

            MainDAL _dal = new MainDAL();
            b = _dal.GetOneBoardToMake(makePicNo);
            AddInfoToBoard(b,true);//附加大版的打印机信息
            if (b == null)//没有可用的格子
            {
                return -4;
            }
            //result = DecryPtPoint(b);
            return result;
        }
        /// <summary>
        /// 附加大版的打印机信息
        /// </summary>
        /// <param name="b"></param>
        private void AddPrinterInfoToBoard(BoardInfo_ProductBigPic b)
        {
            if (b != null && b.ListPhotos.Count > 0)
            {
                using (newSampleYPDBEntities db = new newSampleYPDBEntities())
                {
                    Board bd = db.Board.First(bb => bb.BoardId == b.BoardBaseInfo.BoardId);
                    if (!bd.printerReference.IsLoaded)
                    {
                        bd.printerReference.Load();
                    }
                    printer printer = bd.printer;
                    Printer_Info printerInfo = new Printer_Info()
                    {
                        IsAutoCut = (bool)printer.IsAutoCut,
                        PrinterID = printer.PrinterID,
                        IsMiddlePrint = printer.IsMiddlePrint,
                        IsTransverse = (bool)printer.IsTransverse,
                        PName = printer.PName
                    };
                    b.BoardBaseInfo.Printer = printerInfo;
                }
            }
        }
        /// <summary>
        /// 附加大版的打印机信息
        /// </summary>
        /// <param name="b"></param>
        private void AddInfoToBoard(BoardInfo_ProductBigPic b, bool isPrintTiaoseNo)
        {
            if (b != null && b.ListPhotos.Count > 0)
            {
                using (newSampleYPDBEntities db = new newSampleYPDBEntities())
                {
                    Board bd = db.Board.First(bb => bb.BoardId == b.BoardBaseInfo.BoardId);
                    if (!bd.printerReference.IsLoaded)
                    {
                        bd.printerReference.Load();
                    }
                    printer printer = bd.printer;
                    Printer_Info printerInfo = new Printer_Info()
                    {
                        IsAutoCut = (bool)printer.IsAutoCut,
                        PrinterID = printer.PrinterID,
                        IsMiddlePrint = printer.IsMiddlePrint,
                        IsTransverse = (bool)printer.IsTransverse,
                        PName = printer.PName
                    };
                    b.BoardBaseInfo.Printer = printerInfo;
                    if (isPrintTiaoseNo)
                    {
                        foreach (var photos in b.ListPhotos.GroupBy(p => p.OrderProductId))
                        {
                            WorkOrderFlowList worf = db.WorkOrderFlowList.FirstOrDefault(w => w.orderInfo.OrderProductId == photos.Key && w.tb_Tech.TechType == 4);
                            if (worf != null)
                            {
                                
                                //photos.ToList().ForEach(ph => ph.TiaoseNo = worf.UserId.ToString());
                                foreach (PhotoInfo_ProductBigPic ppbp in photos)
                                {
                                    ppbp.TiaoseNo = worf.UserId.ToString();
                                }
                            }
                        }
                    }
                }
            }
        }


        const int MIN_ASC = 32;
        const int MAX_ASC = 126;
        const int NUM_ASC = 95;
        //解密
        public string Decipher(string strFromText)
        {
            StringBuilder result = new StringBuilder();
            char[] random = _strDogCode.ToCharArray();
            char[] from_text = strFromText.ToCharArray();
            char[] buf1 = new char[10];
            int offset;
            int str_len = 1;
            int i;
            int ch;

            str_len = from_text.Length;

            for (i = 0; i < str_len; i++)
            {
                ch = (int)from_text[i];
                if (ch >= MIN_ASC && ch <= MAX_ASC)
                {
                    ch = ch - MIN_ASC;
                    offset = (NUM_ASC + 1) * random[i];
                    ch = (ch - offset) % NUM_ASC;
                    if (ch < 0)
                    {
                        ch = ch + NUM_ASC;
                    }
                    ch = ch + MIN_ASC;
                    buf1[i] = (char)ch;
                }
                else
                {
                    buf1[i] = from_text[i];
                }
            }
            foreach (var item in buf1)
            {
                result.Append(item);
            }
            return result.ToString();
        }

        public int DecryPtPointAtLocal(BoardInfo_ProductBigPic Board)
        {
            try
            {
                foreach (var pi in Board.ListPhotos)
                {
                    pi.Location = new Point(Convert.ToInt32(Decipher(pi.X)), Convert.ToInt32(Decipher(pi.Y)));
                }
            }
            catch (Exception)
            {
                return -2;
            }
            finally
            {
                //将此板
            }
            return 1;
        }

        //选将坐标解密
        public int DecryPtPoint(BoardInfo_ProductBigPic Board)
        {
            byte[] myReadBuffer = new byte[10240];
            string addr = ConfigurationManager.AppSettings["RemoteIP"].ToString();
            int port = Convert.ToInt32(ConfigurationManager.AppSettings["RemotePort"]);


            string RedStrResult = string.Empty;
            TcpClient client = new TcpClient();
            NetworkStream net = null;
            try
            {
                //int reCount = 0;
                client.Connect(addr, port);
                client.SendTimeout = 600 * 1000;
                client.ReceiveTimeout = 600 * 1000;
                net = client.GetStream();
                net.ReadTimeout = 600 * 1000;

                byte[] myWriteBuffer = Encoding.Unicode.GetBytes(Board.BoardBaseInfo.BoardId.ToString());

                net.Write(myWriteBuffer, 0, myWriteBuffer.Length);

                int tryNum = 0;//只试三次
                while (tryNum < 3)
                {
                    //if (reCount>=4)//重试三次不行就退出
                    //{
                    //    break;
                    //}
                    int redLenth;
                    try
                    {
                        redLenth = net.Read(myReadBuffer, 0, myReadBuffer.Length);
                    }
                    catch (Exception)
                    {
                        return -2;
                    }

                    if (redLenth > 0)
                    {
                        RedStrResult = Encoding.Unicode.GetString(myReadBuffer, 0, redLenth);
                        break;
                    }
                    tryNum++;

                }
                net.Close();

            }
            catch (Exception)
            {
                return -1;
            }
            finally
            {

                client.Close();
                if (net != null)
                {
                    net.Close();
                    net.Dispose();
                }

            }

            if (!string.IsNullOrEmpty(RedStrResult))
            {
                try
                {
                    //分解字符串开如 picmakeupId○x值 ○y值 ¤13○353456346○lksldflsldf
                    string[] picStr = RedStrResult.Split(new char[] { '¤' });
                    foreach (string strPic in picStr)
                    {
                        if (string.IsNullOrEmpty(strPic))
                        {
                            continue;
                        }
                        string[] strT = strPic.Split(new char[] { '○' });
                        int picMarkUpId = Convert.ToInt32(strT[0]);
                        int X = Convert.ToInt32(strT[1]);
                        int Y = Convert.ToInt32(strT[2]);

                        var pi = Board.ListPhotos.First(p => p.PicMakeUpId == picMarkUpId);
                        if (pi != null)
                        {
                            pi.Location = new Point(X, Y);
                        }
                    }
                }
                catch (Exception)
                {

                    return -2;
                }
                return 1;
            }
            return -1;
        }

        /// <summary>
        /// 生成大图成功后更改大图的状态以及照片的状态还有流程的状态
        /// </summary>
        /// <param name="p"></param>
        /// <param name="p_2"></param>
        /// <returns>1:代表正常,-1:大板存在，-2：照片不存在；-3：执行操作时出错</returns>
        public int MakeBigPicSusscess(int BoardId, string newPicPath)
        {
            int result = 1;
            if (BoardId > 0)
            {
                MainDAL _mainDal = new MainDAL();
                result = _mainDal.MakeBigPicSusscess(BoardId, newPicPath);
            }
            else
            {
                result = -1;//参数不正确
            }
            return result;
        }

        public void SetBoardStatus(int boardId, int boardStatus, string remark)
        {
            MainDAL _mainDal = new MainDAL();
            _mainDal.SetBoardStatus(boardId, boardStatus, remark);
        }
        public void SetBoardAutoCutInfo(int inBoardId, string inStr)
        {
            MainDAL _mainDal = new MainDAL();
            _mainDal.SetBoardAutoCutInfo(inBoardId, inStr);
        }

       
    }
}
